var bus = {
	success: '0000',
	setTitle: function (str) {
	  document.title = str;
	  var i = document.createElement('iframe');
	  i.src = '//m.baidu.com/favicon.ico';
	  i.style.display = 'none';
	  i.onload = function() {
	    setTimeout(function(){
	      i.remove();
	    }, 9)
	  }
	  document.body.appendChild(i);
	},
	showTip: function (str, callback) {//提示框
		if(str && str.length > 0){
			var tip = '<div class="errTip"><span>'+ str +'</span></div>';
			$('body').append(tip);
			setTimeout(function() {
				$('.errTip').remove();
				if(callback){
					callback();
				};
			},1200);
		};
	},
	getDate: function () { //获取当前时间年月日
		var date = new Date();
		var day = date.getDate();
		var month = date.getMonth()+1;
		if(day < 10) {
			day = '0' + day
		}
		if(month < 10) {
			month = '0' + month
		}
		
		return date.getFullYear() + '-' + month + '-' + day;
	},
	loading: function (isShow, text) {
		var html = '<div class="loading">'+
						'<div class="spinner full">'+
							'<div class="bar1 rounds"></div>'+
					        '<div class="bar2 rounds"></div>'+
					        '<div class="bar3 rounds"></div>'+
					        '<div class="bar4 rounds"></div>'+
					        '<div class="bar5 rounds"></div>'+
					        '<div class="bar6 rounds"></div>'+
					        '<div class="bar7 rounds"></div>'+
					        '<div class="bar8 rounds"></div>'+
					        '<div class="bar9 rounds"></div>'+
					        '<div class="bar10 rounds"></div>'+
					        '<div class="bar11 rounds"></div>'+
					        '<div class="bar12 rounds"></div>'+
					        '<p class="loadtext">'+ text +'</p>'+
						'</div>'+
					'</div>';
		if(isShow){
			$('body').append(html);
		}else{
			$('.loading').remove();
		};
	},
	pop: function (options) {
		var html = title = contents = buttons = '';
		title = options.title ? '<h1 class="pop-title">'+ options.title +'</h1>' : '';
		contents = '<div class="tip-content" style="text-align: '+ options.align +'">'+ options.content +'</div>';
		for(var i = 0; i < options.buttonText.length; i++) {
			if(options.buttonText.length > 1){
				buttons += '<button class="btns btns-width" data-index="'+ i +'">'+ options.buttonText[i] +'</button>';
			}else{
				buttons = '<button class="btns btn-width" data-index="'+ i +'">'+ options.buttonText[i] +'</button>';
			};
		};
		html = '<div class="pop close-pop">'+
					'<div class="pop-content center">'+
						title + contents +
						'<div class="group-btn">'+
							buttons +
						'</div>' +
					'</div>'+
				'</div>';
		
		$('body').append(html);
		
		$('.group-btn').on('click',function (e) {
			var ev = e || window.event;
			var el = ev.srcElement || ev.target;
			options.handleClick(el.dataset.index, $(el).text(), function () {
				$('.close-pop').remove();
			});
		});
	},
	loadData: function (clientHeight, scrollHeight, scrollTop, loadMore) {
		if (scrollHeight - scrollTop - clientHeight <= 10) {
			loadMore();
		};
	},
	getScrollTop: function () {
	    var scrollTop = 0;
	    if (document.documentElement && document.documentElement.scrollTop) {
	      	scrollTop = document.documentElement.scrollTop;
	    } else if(document.body) {
	      	scrollTop = document.body.scrollTop;
	    };
	    return scrollTop;
	},
	getClientHeight: function () {
	    var clientHeight = 0;
	    if (document.body.clientHeight && document.documentElement.clientHeight) {
	      	clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
	    } else {
	      	clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
	    };
	    return clientHeight;
	},
	getScrollHeight: function () {
			return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
	},
	arrSort: function (str) { //数组对象排序
	    return function(a,b){
	        var value1 = a[str];
	        var value2 = b[str];
	        return value2 - value1;
	    }
	},
	cleanArray: function (arr) { //数组去重
		var temp = [];
		for(var i = 0; i < arr.length; i++) {
			if(temp.indexOf(arr[i]) == -1) {
				temp.push(arr[i]);
			};
		};
		return temp;
	},
	mobile: function (str) { //手机号码验证
		var pattern = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
		return pattern.test(str);
	},
	isCardNo: function (str) { //身份证验证
		//身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X 
		var pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; 
		return pattern.test(str);
	},
	analyzeIDCard: function (IDCard) { //根据身份证号得到姓别和精确计算年龄
		var sexAndAge = {};
		//获取用户身份证号码
		var userCard = IDCard;
		//如果身份证号码为undefind则返回空
		if(!userCard){
			return sexAndAge;
		}
		//获取性别
		if(parseInt(userCard.substr(16,1)) % 2 == 1){
			sexAndAge.sex = '1（男）'
		}else{
			sexAndAge.sex = '0（女）'
		}
		//获取出生年月日
		//userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
		var yearBirth = userCard.substring(6,10);
		var monthBirth = userCard.substring(10,12);
		var dayBirth = userCard.substring(12,14);
		//获取当前年月日并计算年龄
		var myDate = new Date();
		var monthNow = myDate.getMonth() + 1;
		var dayNow = myDate.getDay();
		var age = myDate.getFullYear() - yearBirth;
		if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
			age--;
		}
		//得到年龄
		sexAndAge.age = age;
		//返回性别和年龄
		return sexAndAge;
	},
	setLocal: function (name, value) {//存入local生命周期是永久，这意味着除非用户显示在浏览器提供的UI上清除localStorage信息，否则这些信息将永远存在。
		localStorage.setItem(name, value);
	},
	getLocal: function (c_name) {//取出local
		return localStorage.getItem(c_name);
	},
	delLocal: function (name) { //删除local
		if(name) {
			localStorage.removeItem(name);//删除指定local
		} else {
			localStorage.clear();//删除所有local
		};
	},
	setSession: function (name, value) {//存入session生命周期为当前窗口或标签页，窗口或标签页被永久关闭，所有sessionStorage存储的数据就清空。
		sessionStorage.setItem(name, value);
	},
	getSession: function (c_name) {//取出session
		return sessionStorage.getItem(c_name);
	},
	delSession: function (name) { //删除session
		if(name) {
			sessionStorage.removeItem(name);//删除指定session
		} else {
			sessionStorage.clear();//删除所有session
		};
	},
	setCookie: function (name, value, time) { //存入cookie可以设置生命周期，存储在硬盘上过期清除，开关机都会存在，如不设则浏览器关掉就清除，存储在内存。
		// 设置名称为name,值为value的Cookie
		var expdate = new Date(); // 初始化时间
		expdate.setTime(expdate.getTime() + time); // 时间单位毫秒
		document.cookie = name + '=' + value + ';expires=' + expdate.toGMTString() + ';path=/';
		// 即document.cookie= name+"="+value+";path=/";时间默认为当前会话可以不要，但路径要填写，因为JS的默认路径是当前页，如果不填，此cookie只在当前页面生效！
	},
	getCookie: function (c_name) { //取出cookie
		if(document.cookie.length > 0) {
			var c_start = document.cookie.indexOf(c_name + '=');
			if(c_start != -1) {
				c_start = c_start + c_name.length + 1;
				var c_end = document.cookie.indexOf(';', c_start);
				if(c_end == -1) c_end = document.cookie.length;
				return unescape(document.cookie.substring(c_start, c_end));
			};
		};
		return '';
	},
	getParam: function (urlParam) { //获取Url参数，返回对象
		var theRequest = new Object();
		if(urlParam.indexOf('?') != -1) {
			var str = urlParam.substr(1);
			var strs = str.split('&');
			for(var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split('=')[0]] = (strs[i].split('=')[1]);
			};
		};
		return theRequest;
	},
	send:function (config) { //ajax封装
		var that = this;
		if(config.share){
			var baseUrl = 'http://www.string-tech.cn';//分享
		}else{
			var baseUrl = '';//http://192.168.5.129:8997
		};
		var token = that.getSession('token');
		var seting = {};
		if(config.type == 'post' || config.type == 'POST'){
			if(!config.files){//非文件类型
				seting = {
					type: config.type,
					url: baseUrl + config.url,
					async: config.async,
					data: JSON.stringify(config.data),
					dataType: 'json',
					contentType: 'application/json;charset=UTF-8',
					beforeSend: function (XMLHttpRequest) {//请求头加token
	                    XMLHttpRequest.setRequestHeader("authorization", token);
	                },
					success: function (res) {
						config.success(res);
					},
					error: function (res) {
						console.log(res);
					}
				};
			}else{//文件类型
				seting = {
					type: config.type,
					url: baseUrl + config.url,
					async: config.async,
					data: config.data,
					dataType: 'json',
					contentType: false,
	  				processData: false,
	  				beforeSend: function (XMLHttpRequest) {//请求头加token
	                    XMLHttpRequest.setRequestHeader("authorization", token);
	                },
					success: function (res) {
						config.success(res);
					},
					error: function (res) {
						console.log(res);
					}
				};
			};
		}else{
			seting = {
				type: config.type,
				url: baseUrl + config.url,
				async: config.async,
				data: config.data,
				dataType: 'json',
				beforeSend: function (XMLHttpRequest) {//请求头加token
                    XMLHttpRequest.setRequestHeader("authorization", token);
                },
				success: function (res) {
					config.success(res);
				},
				error: function (res) {
					console.log(res);
				}
			};
		};
		$.ajax(seting);
	},
	
	encode: function (input) { //加密
  		var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
      	var output = "", utftext = "", str = "";
      	var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
      	var i = 0;
      	if(typeof(input) != 'string'){//不是字符串，转为字符串形式加密
      		str = JSON.stringify(input).replace(/\r\n/g,"\n");
      	}else{
      		str = input.replace(/\r\n/g,"\n");
      	};
      	for (var n = 0; n < str.length; n++) {
          	var c = str.charCodeAt(n);
          	if (c < 128) {
              	utftext += String.fromCharCode(c);
          	} else if((c > 127) && (c < 2048)) {
              	utftext += String.fromCharCode((c >> 6) | 192);
              	utftext += String.fromCharCode((c & 63) | 128);
          	} else {
              	utftext += String.fromCharCode((c >> 12) | 224);
              	utftext += String.fromCharCode(((c >> 6) & 63) | 128);
              	utftext += String.fromCharCode((c & 63) | 128);
          	};
      	};
      	while (i < utftext.length) {
          	chr1 = utftext.charCodeAt(i++);
          	chr2 = utftext.charCodeAt(i++);
          	chr3 = utftext.charCodeAt(i++);
          	enc1 = chr1 >> 2;
          	enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
          	enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
          	enc4 = chr3 & 63;
          	if (isNaN(chr2)) {
              	enc3 = enc4 = 64;
          	} else if (isNaN(chr3)) {
              	enc4 = 64;
          	};
          	output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
      	};
      	return output;
  	},
  	decode: function (input) { //解密
  		var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
      	var output = "", str = "";
      	var n = 0;
      	var c = 0, c1 = 0, c2 = 0, c3 = 0;
      	var i = 0;
      	var chr1, chr2, chr3;
      	var enc1, enc2, enc3, enc4;
      	var _input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
      	while (i < _input.length) {
          	enc1 = _keyStr.indexOf(_input.charAt(i++));
          	enc2 = _keyStr.indexOf(_input.charAt(i++));
          	enc3 = _keyStr.indexOf(_input.charAt(i++));
          	enc4 = _keyStr.indexOf(_input.charAt(i++));
          	chr1 = (enc1 << 2) | (enc2 >> 4);
          	chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
          	chr3 = ((enc3 & 3) << 6) | enc4;
          	output = output + String.fromCharCode(chr1);
          	if (enc3 != 64) {
              	output = output + String.fromCharCode(chr2);
          	};
          	if (enc4 != 64) {
              	output = output + String.fromCharCode(chr3);
          	};
      	};
      	while (n < output.length) {
          	c = output.charCodeAt(n);
          	if (c < 128) {
              	str += String.fromCharCode(c);
              	n++;
          	} else if((c > 191) && (c < 224)) {
              	c2 = output.charCodeAt(n+1);
              	str += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
              	n += 2;
          	} else {
              	c2 = output.charCodeAt(n+1);
              	c3 = output.charCodeAt(n+2);
              	str += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
              	n += 3;
          	};
      	};
      	return str;
  	}
};
